<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('采购计划')"/>
    <th:block th:include="include :: businessCSS"/>
    <style>
        .main-content {
            position: relative;
        }

        .topbtns {
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 9999;
            background-color: #fff;
        }

        .preservationBtn {
            padding: 10px;
            margin: 0;
            position: fixed;
            top: 0;
            z-index: 9999;
            background: #fff;
            width: 100%;
        }

        .preservationBtn input {
            font-size: 16px;
            background-color: rgb(80, 138, 238);
            color: #fff;
            border: none;
            padding: 5px 30px;
            border-radius: 5px;
            cursor: pointer;
        }

        /* .layui-border-box{height: 350px !important;}
        .layui-table-body{height: 240px !important;} */
        .layui-table-tool-temp {
            padding-right: 30px;
        }

        .getDetailUpload, .getDetailUpload2 {
            cursor: pointer;
        }

        .layui-table-tool-self {
            display: none;
        }

    </style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
    <div class="main-content">
        <form class="layui-form head-form">
            <div class="topbtns">
                <th:block th:include="include :: business_btn"/>
            </div>
            <div class="north" style="background-color: #fff;margin-top: 55px;">
                <!-- <div class="layui-form-item preservationBtn">
                    <button class="layui-btn layui-btn-normal dhicon" type="button" lay-submit lay-filter="btn-edit" id="btn-edit">保存</button>
                    <button class="layui-btn layui-btn-normal dhicon" type="button" lay-submit lay-filter="btn-sh" id="btn-sh">审核</button>
                    <button class="layui-btn layui-btn-normal dhicon" type="button" lay-submit lay-filter="btn-del" id="btn-del">删除</button>
                </div>
                <div style="width: 100%;height: 65px;background: #f6f6f6;"></div> -->
                <div class="forminput"></div>
            </div>
            <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
            <div>
                <table class="layui-hide" id="mjdhtable" lay-filter="mjtable"></table>
                <!-- <script type="text/html" id="barDh">
                    <button class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" th:disabled="${enableEdit} == 1 ?false:true" lay-event="del">&nbsp;删除</button>
                </script> -->
                <script type="text/html" id="zjtoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div style="font-weight: 700;font-size: 18px;">母件列表</div>
                        <div>
                            <button class="layui-btn layui-btn-normal dhicon"
                                    th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button"
                                    th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增
                            </button>
                            <button class="layui-btn layui-btn-danger dhicon"
                                    th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button"
                                    th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除
                            </button>
                        </div>
                    </div>
                </script>
            </div>

            <div>
                <table class="layui-hide" id="zjdhtable" lay-filter="zjtable"></table>
                <script type="text/html" id="jptoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div style="font-weight: 700;font-size: 18px;">子件列表</div>
                    </div>
                </script>
            </div>
            <th:block th:include="include :: pageFooter"/>
        </form>
    </div>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: businessJS"/>
<th:block th:include="include :: inlineJS"/>

<script th:inline="javascript">
    /*<![CDATA[*/
    var prefix = ctx + "business/productbasis",
        prefix2 = ctx + "base/company";

    var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
    var fieldsHiddenList = [[${fieldsHiddenList}]];
    var moduleTable = [[${moduleTable}]];
    var enableEdit = [[${enableEdit}]];
    //母件表格基础信息
    var gridColumns = [[${gridColumns}]];
    //母件表格基础信息
    var gridColumnsZJ = [[${gridColumnsZJ}]];
    // 母件列表数据
    var List = [[${List}]];
    //子件列表数据
    var sonList = [[${sonList}]];
    console.log("sonList",sonList)
    var $, layer, form, table, nid, noTable;
    layui.use(['laydate', 'form', 'layer', 'jquery', 'util', 'element', 'upload', 'table'], function () {
        $ = layui.$, layer = layui.layer, form = layui.form, laydate = layui.laydate, util = layui.util, element = layui.element, upload = layui.upload, table = layui.table;
        beforeInit();//表单初始化之前的动作集合
        //初始化操作
        headcom3()
        nid = $('#nid').val()
        // 保存按钮事件变化
        $(function () {
            $('.tp-save').attr('onclick', '')
            $('.tp-save').attr('lay-filter', 'btn-edit')
            $('.tp-save').attr('lay-submit', true)
            $('.tp-delete').attr('onclick', '')
            $('.tp-delete').attr('lay-filter', 'btn-delete')
            $('.tp-delete').attr('lay-submit', true)
        })


        // 保存操作
        form.on('submit(btn-edit)', function (data) {
            var is_return = false//是否中断保存
            fieldsList.map((v, i) => {
                if (v.fieldFrontRequired) {
                    if (!$('#' + v.fields).val()) {
                        layer.msg(v.fieldName + '不能为空')
                        is_return = true
                    }
                }
            })

            listData1.map((v, i) => {
                v.iid = i + 1
            })
            listData2.map((v, i) => {
                v.iid = i + 1
                if (!Number.isInteger(v.allNum)){
                    layer.msg('子件总数需为整数！');
                    is_return = true
                }

                if (!(v.num > 0)){
                    layer.msg('子件数量不可为0！');
                    is_return = true
                }

                if (!(v.prices > 0)){
                    layer.msg('子件预估单价不可为0！');
                    is_return = true
                }
            })
            if (is_return) return;
            $.modal.loading("正在处理中，请稍后...");
            $.post("/purchase/purchaseplan/editpost", {
                infoMap: JSON.stringify(data.field),
                infoItems: JSON.stringify(listData1),
                sonData: JSON.stringify(listData2)
            }, function (res) {
                $.modal.closeLoading()
                layer.msg(res.msg);
                if (res.code == 0) {
                    window.location.href = '/purchase/purchaseplan/edit?nid=' + res.data;
                }
            });
        });

        // 删除操作
        form.on('submit(btn-delete)', function(data){
            console.log("执行删除")
            if(!nid || nid==0){
                layer.msg('请先保存数据')
            }else{
                layer.confirm('是否确定删除', {btn : ['确定', '取消']}, function() {
                    $.modal.loading("正在处理中，请稍后...");
                    $.get("/purchase/purchaseplan/delete",{nid},function(res){
                        $.modal.closeLoading()
                        layer.msg(res.msg);
                        if(res.code==0){
                            window.location.href = '/purchase/purchaseplan/edit?nid=0';
                        }
                    });
                });

            }
        });


        var listData1 = List ? List : []
        var listData2 = sonList ? sonList : []
        // 初始化表格
        $.tablelist.init({
            elem: '#mjdhtable'
            , data: listData1
            , page: false
            , even: true
            , limit: 10000
            , totalRow: gridColumns.totalRow
            , cols: [gridColumns.gridBody]
            , toolbar: '#zjtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '320'
            , done: function (res, curr, count) {
                listData1 = table.cache.mjdhtable;//每次重载都赋值更新表缓存
            }, success: function (a, b, c) {
                // console.log(a, b, c, 9999)
            }
        });
        $.tablelist.init({
            elem: '#zjdhtable'
            , data: listData2
            , page: false
            , even: true
            , limit: 10000
            , totalRow: gridColumnsZJ.totalRow
            , cols: [gridColumnsZJ.gridBody]
            , toolbar: '#jptoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '300'
            , done: function (res, curr, count) {
                listData2 = table.cache.zjdhtable;//每次重载都赋值更新表缓存
            }
        });

        //监听单元格编辑
        table.on('edit(mjtable)', function (obj) {
            calculation()
        });

        //监听单元格编辑
        table.on('edit(zjtable)', function (obj) {
            var jgSl = 0
            var cgSl = 0
            var prices = 0
            if (obj.data.jgSl) jgSl = obj.data.jgSl
            if (obj.data.cgSl) cgSl = obj.data.cgSl
            if (obj.data.prices) prices = obj.data.prices
            allNum = (+jgSl) + (+cgSl)
            totalPrices = numWay((+allNum) * (+prices));
            // console.log("22",Math.floor((+allNum) * (+prices)))
            obj.update({allNum: allNum, totalPrices: totalPrices});
            caigou()
        });

        //  赋值采购计划金额
        function caigou() {
            var num = 0
            listData2.map((n, m) => {
                num = num + (+n.totalPrices)
            })
            $('#planCost').val(num)
        }

        // 根据采购计算联动子表格
        function calculation() {
            var spSl = 0
            listData1.map((v, i) => {
                if (v.spSl) {
                    spSl = v.spSl
                    listData2.map((n, m) => {
                        if (v.spBm === n.fBm) {
                            n.cgSl = (+spSl) * (+n.num)
                        }
                        console.log(spSl, n.num, n.cgSl)
                    })
                } else {
                    spSl = 0
                    listData2.map((n, m) => {
                        if (v.spBm === n.fBm) {
                            n.cgSl = (+spSl) * (+n.num)
                        }
                    })
                }
            })
            listData2.map((v, i) => {
                var jgSl = 0
                var cgSl = 0
                var allNum = 0
                if (v.jgSl) jgSl = v.jgSl
                if (v.cgSl) cgSl = v.cgSl
                // if (v.allNum || v.allNum==0) cgSl = v.allNum
                v.prices = v.prices ? v.prices : v.bPrice
                v.allNum = (v.jgSl ? v.jgSl : jgSl)*1 + (v.cgSl ? v.cgSl : cgSl)*1
                v.totalPrices = 1*((+v.allNum) * (+v.prices)).toFixed(2)
            })
            console.log("listData2-2", listData2)
            table.reload('zjdhtable', {data: listData2});
            caigou()
        }

        //母件表格操作
        table.on('toolbar(mjtable)', function (obj) {
            var selectedObject = ""
            sessionStorage.setItem('mjdata', JSON.stringify(table.cache.mjdhtable))
            table.cache.mjdhtable.map((v, i) => {
                if (selectedObject) {
                    selectedObject += ',' + v.spBm
                } else {
                    selectedObject += v.spBm
                }
            })
            switch (obj.event) {

                case 'addbtn':
                    // if( $('#vGsBm').val() === "" ){
                    //     return layer.msg("请先选择采购公司!");
                    // }
                    layer.open({
                        type: 2,
                        area: [($(window).width() - 200) + 'px', ($(window).height() - 100) + 'px'],
                        fix: false,//不固定
                        offset: '10%',//距离顶部
                        maxmin: true,//最大最小化
                        shade: 0.3,//遮罩
                        title: '母件列表',
                        content: "/purchase/purchaseplan/select2?pagetype=checkbox&by=direct&fmoduleTable=" + moduleTable + "&selectedObject=" + selectedObject,
                        // + "&vGsBm=" + $('#vGsBm').val()
                        btn: ['确定', '取消'],
                        shadeClose: true,// 弹层外区域关闭
                        yes: function (index, layero) {
                            console.log('click---yes');
                            var res = window["layui-layer-iframe" + index].callbackdata();
                            if (res.length > 0) {
                                var pcode = ""
                                $.each(res, function (i, v) {
                                    v.spBm = v.code
                                    v.spMc = v.name
                                    v.kcSl = v.productNum
                                    if (pcode) {
                                        pcode += ',' + v.spBm
                                    } else {
                                        pcode += v.spBm
                                    }
                                })
                                layer.closeAll();
                                var mjdata = sessionStorage.getItem('mjdata')
                                if (mjdata) {
                                    mjdata = JSON.parse(mjdata)
                                    let newall = []
                                    let endData = [];
                                    var isdata = false
                                    for (let i = 0; i < res.length; i++) {
                                        var isdata = false
                                        if (newall.indexOf(res[i].spBm) === -1) {
                                            for (let n = 0; n < mjdata.length; n++) {
                                                if (newall.indexOf(res[i].spBm) === -1) {
                                                    if (res[i].spBm == mjdata[n].spBm) {
                                                        isdata = true
                                                        endData.push(mjdata[n]);
                                                        newall.push(mjdata[n].spBm);
                                                    }
                                                }
                                            }
                                            if (!isdata) {
                                                endData.push(res[i]);
                                                newall.push(res[i].spBm);
                                            }
                                        }
                                    }
                                    table.reload('mjdhtable', {data: endData});
                                } else {
                                    table.reload('mjdhtable', {data: res});
                                }

                                $.get('/business/productactive/listzj2?pcode=' + pcode, function (res) {
                                    listData2 = res.data
                                    calculation()
                                });
                            } else {
                                layer.msg("请选择数据");
                            }
                        }
                    });
                    break;

                case 'mjbtn_save':
                    var objdata = table.checkStatus('mjdhtable')
                    objdata = objdata.data
                    listData1 = table.cache.mjdhtable;
                    listData2 = table.cache.zjdhtable;
                    if (objdata.length > 0) {
                        objdata.forEach(item => {
                            listData1 = listData1.filter(items => items.spBm != item.spBm);
                        });
                        objdata.forEach(item => {
                            listData2 = listData2.filter(items => items.fBm != item.spBm);
                        });
                        table.reload('mjdhtable', {data: listData1});
                        table.reload('zjdhtable', {data: listData2});
                    } else {
                        layer.msg("请选择数据");
                    }
                    break;
            };
        });


        $(".fieldsimg").each(function () {
            var id = $(this).attr('name')
            upload.render({
                elem: '#' + id + '_upimg',
                url: '/system/fileinfo/uploadmailimg',
                accept: 'images',
                before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        console.log(index, file, result)
                    });
                },
                done: function (res) {
                    //如果上传失败
                    if (res.errno > 0) {
                        return layer.msg('上传失败');
                    } else {
                        layer.msg('上传成功');
                        $('#' + id).val(res.data[0])
                        layui.$('#' + id + '_upimg').find('.upicon').addClass('layui-hide')
                        layui.$('#' + id + '_upimg').find('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.data[0]);
                    }
                }, error: function (err) {
                    //演示失败状态，并实现重传
                    console.log(err)
                }
            });
        })


        $('.t_date').each(function () {
            var datetype = $(this).attr('datetype')
            laydate.render({
                elem: this,
                type: datetype == 't_date' ? 'date' : datetype == 't_datetime' ? 'datetime' : datetype == 't_year' ? 'year' : 'month'
            })
        })

        $.get("/purchase/purchaseplan/listbynid?nid=" + nid, function (res) {
            noTable = res.data;
        });
    });

    function getMoreAfter(fieldsList, fields, tindex, fieldName, fieldSearchType, isSearch, isLayer, res) {
        // console.log("res",fieldsList,fields,tindex,fieldName,fieldSearchType,isSearch,isLayer,res)
        if (fields === 'vGsDz') {
            $('#vGsDz').val(res.vGjH + ',' + res.vSfH + ',' + res.vDsH + ',' + res.vCqH + ',' + res.vDzH)
            $('#addressId').val(res.guid)
        }
        else if(fields === 'vGsMc') {
        	if(res.vGsSh == null || res.vGsSh == '') {
                layer.msg('请先完善该公司税号');
                $('#vGsMc').val('');
                $('#vGsJc').val('');
                $('#vGsBm').val('');
        	}
        }
    }

    function numWay(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf(".");
        if (rs < 0) {
            rs = s.length;
            s += ".";
        }
        while (s.length <= rs + 2) {
            s += "0";
        }
        return s;
    }


</script>

</body>
</html>